package ArticleService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

func Add(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	data["create_at"] = time.Now().Unix()
	// 增加附加数据
	if req.AddInsertData != nil {
		otherData := req.AddInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 添加前方法
	if req.AddBeforeFn != nil {
		respRes := req.AddBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}

	// 别名不重复
	alias := r.GetString("alias")
	if alias == "" {
		return response.FailByRequestMessage(nil, "别名不能为空")
	}
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where("alias", alias).
		Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if count > 0 {
		return response.FailByRequestMessage(nil, "别名重复")
	}
	delete(data, "content")
	delete(data, "type")
	data, err = toolsDb.FilterColumnParams(g.DB(), false, data, req.TableName)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Insert(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	id, err := res.LastInsertId()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 插入 article_content
	res, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "article_content").Insert(g.Map{
		"article_id": id,
		"content":    r.GetString("content"),
	})
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "添加成功", g.Map{
		"id": id,
	})
}
